<template>
  <div class="sort-container">
    <draggable v-model="dataList" class="sort-list" draggable=".sort-item" @start="drag=true" @end="drag=false">
      <div
        v-for="(item,index) in dataList"
        :key="index"
        :class="{'sort-item':true,'sort-new':!item.id}"
      >
        <input v-model="item.modelName" clearable class="item-input">
        <div class="item-name">{{ item.indexName }}</div>
      </div>
    </draggable>
    <div class="sort-bottom" style="text-align:right;">
      <el-button size="small" @click="handleCancel">取消</el-button>
      <el-button size="small" type="primary" @click="handleSave">确定</el-button>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  components: { draggable },
  props: {
    list: {
      type: Array,
      default: () => { return [] }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dataList: [],
      dragDom: null
    }
  },
  watch: {
    visible: {
      handler(newval, oldval) {
        if (newval) {
          this.initDataList()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    initDataList() {
      const { list } = this
      if (list.length > 0) {
        this.dataList = [].concat(list)
        this.dataList.forEach(i => {
          i.modelName = i.modelName || ''
        })
      }
    },
    handleCancel() {
      this.$emit('close')
    },
    handleSave() {
      this.$emit('save', this.dataList)
      this.$nextTick(() => {
        this.handleCancel()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.sort-container{
    .sort-list{
        max-height: 500px;
        overflow-y: scroll;
        padding: 0 10px;
    }
    .sort-item{
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        background: #f1f2fd;
        height: 40px;
        box-sizing: border-box;
        transition: 0.3s;
        cursor: move;
        font-size: 14px;
        border-radius: 10px;
        .item-name{
            flex: 1;
            margin-left:10px;
        }
        .item-input{
            width: 20%;
            height: 100%;
            border: 1px solid #ddd;
        }
    }
    .sort-new{
        background: #f5dbd6;
    }
}
</style>

